Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
Error [ERR_HTTP_HEADERS_SENT] while trying to login with wrong password

As backend for react, I have node v16.13.0 and express 4.17.2 and this express route for login

router.post("/login", async (req, res) => {
     try {
      const user = await User.findOne({ email: req.body.email });
      !user && res.status(404).json("user not found");
  
      const validPassword = await bcrypt.compare(req.body.password, user.password)

      !validPassword && res.status(400).json("wrong password")
  
      res.status(200).json(user)
    } catch (err) {
      res.status(500).json(err)
    }
  });

It works fine when the credentials are correct, but when the password is wrong I get:

::ffff:127.0.0.1 - - [05/Feb/2022:14:50:33 +0000] "POST /api/auth/login HTTP/1.1" 500 16
node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:776:10)
    at ServerResponse.send (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:267:15)
    at /home/me/Desktop/myapp/api/routes/auth.js:49:23
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

I'm wondering what is wrong here and how can i fix it?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

when you pass the wrong credentials the res.json will be called twice and the error says that.

router.post("/login", async (req, res) => {
     try {
      const user = await User.findOne({ email: req.body.email });
      if(!user) {
         return res.status(404).json("user not found");
      }
  
      const validPassword = await bcrypt.compare(req.body.password, user.password)

      if(!validPassword) {
        return res.status(400).json("wrong password")
      } 
  
      res.status(200).json(user)
    } catch (err) {
      res.status(500).json(err)
    }
  });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!